package com.treasure.common.utils;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sunhongmin
 * @date 2023/8/25 22:47
 * @description
 */
@UtilityClass
@Slf4j
public class ResourceReader {

    public static String readStringFromResource(String resourcePath) throws IOException {
        InputStream resourceStream = ClassLoader.getSystemResourceAsStream(resourcePath);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Objects.requireNonNull(resourceStream);
        try {
            byte[] tempArray = new byte[1024];
            int len = 0;
            while ((len = resourceStream.read(tempArray)) != -1) {
                byteArrayOutputStream.write(tempArray, 0, len);
            }
        } finally {
            resourceStream.close();
            byteArrayOutputStream.close();
        }
        return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
    }


    public static String getFileName(String filePath) {
        int slashIndex = filePath.lastIndexOf("/");
        if (slashIndex == -1) {
            return filePath;
        }
        return filePath.substring(slashIndex + 1);
    }


    /**
     * 读取输入流中的文本，并按照段落切分
     * @param in 输入流
     * @return 段落文本
     */
    public static List<String> readAndSplitParagraphs(InputStream in) {
        List<String> paragraphs = new ArrayList<>();
        StringBuilder paragraph = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.trim().isEmpty()) {
                    // 遇到空行，将段落添加到列表中，并重置段落
                    if (paragraph.length() > 0) {
                        paragraphs.add(paragraph.toString());
                        paragraph.setLength(0);
                    }
                } else {
                    // 将非空行添加到当前段落
                    paragraph.append(line).append(System.lineSeparator());
                }
            }

            // 处理最后一个段落
            if (paragraph.length() > 0) {
                paragraphs.add(paragraph.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("readAndSplitParagraphs error: ", e);
        }

        return paragraphs;
    }

}
